package com.zzq.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@Slf4j
public class RedisConfiguration {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        log.info("开始创建redis模板对象...");
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        // 设置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 设置key的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 设置hash key的序列化方式
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        // 创建并配置ObjectMapper
        ObjectMapper objectMapper = createObjectMapper();

        // 使用推荐的GenericJackson2JsonRedisSerializer替代Jackson2JsonRedisSerializer
        GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer(objectMapper);

        // 设置value的序列化方式
        redisTemplate.setValueSerializer(serializer);
        // 设置hash value的序列化方式
        redisTemplate.setHashValueSerializer(serializer);

        // 初始化RedisTemplate
        redisTemplate.afterPropertiesSet();

        log.info("redis模板对象创建完成...");
        return redisTemplate;
    }

    // 创建并配置ObjectMapper
    private ObjectMapper createObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 注册Java 8时间模块（处理LocalDateTime等类型）
        objectMapper.registerModule(new JavaTimeModule());
        // 禁用日期时间戳格式（使用ISO-8601格式）
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        // 可选：启用空值处理
        // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return objectMapper;
    }
}
